﻿namespace Groundwork.Core.Threading
{
	using System;
	using System.Threading;

	/// <summary>
	/// Description of AutoReset.
	/// </summary>
	public class ThreadLocking : IDisposable
	{
		private static AutoResetEvent resetEvent = new AutoResetEvent(false);
		private string methodName = string.Empty;
		
		/// <summary>
		/// Default Expiry is 30 seconds
		/// </summary>
		/// <param name="method"></param>
		public ThreadLocking(string method)
		{	
			TimeSpan expiry = TimeSpan.FromSeconds(30);
            methodName = method;
			Console.WriteLine("AutoResetEvent set on {0}", methodName);
			resetEvent.WaitOne(expiry);
		}
		
		public void Release()
		{
			Console.WriteLine("AutoResetEvent released manually on {0}", methodName);
			resetEvent.Set();
		}
		
		public ThreadLocking(string method, TimeSpan expiry)
		{
            methodName = method;
			Console.WriteLine("AutoResetEvent set on {0}", methodName);
			resetEvent.WaitOne(expiry);
		}
		
		public void Dispose()
		{
			Console.WriteLine("AutoResetEvent released on {0}", methodName);
			resetEvent.Set();
		}
	}
}
